/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.hnilica.cisteniulic.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.hnilica.cisteniulic.dao.ConnectionPool;
import net.hnilica.cisteniulic.dao.DBUtil;

/**
 *
 * @author swosh
 */
public class Activation extends HttpServlet {

    private static final String url = "/CisteniUlic/index.jspx?akce=activation";
    private Logger log;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String aktHashHex = request.getParameter("aktHashHex");
        ConnectionPool pool = ConnectionPool.getInstance();
        Connection connection = pool.getConnection();
        PreparedStatement ps = null;
        String urlFinal = url + "&success=failed";

        ResultSet rs;
        String role = null;
        String querySel = "select \"role\"  from osoba_role "
                + "where email = (select email from osoba where akt_hash = ?)";
        try {
            ps = connection.prepareStatement(querySel);
            ps.setString(1, aktHashHex);
            rs = ps.executeQuery();
            rs.next();
            role = rs.getString("role");


        } catch (SQLException e) {
            rollback(connection);
            log.log(Level.SEVERE, "Chyba při aktivaci účtu.", e);
        } finally {
            DBUtil.closePreparedStatement(ps);
            // Dont freeConnection(connection);
        }



        if ("nereg_uzivatel".equals(role)) {
            int numUpdated = 0;
            boolean isUpdated = false;
            String isUpdatedS;
            String queryUpd = "UPDATE osoba_role SET \"role\"='uzivatel'::varchar "
                    + "where \"role\"='nereg_uzivatel'::varchar and email = (select email from osoba where akt_hash = ?)";
            try {
                ps = connection.prepareStatement(queryUpd);
                ps.setString(1, aktHashHex);
                numUpdated = ps.executeUpdate();

                isUpdated = (numUpdated == 1) ? true : false;
                if (isUpdated) {
                    connection.commit();
                } else {
                    rollback(connection);
                }
            } catch (SQLException e) {
                rollback(connection);
                log.log(Level.SEVERE, "Chyba při aktivaci účtu.", e);
            } finally {
                DBUtil.closePreparedStatement(ps);
                pool.freeConnection(connection);
            }
            if (isUpdated) {
                urlFinal = url + "&success=registred";
            }
        } else {
            urlFinal = url + "&success=beforeRegistred";
        }

        response.sendRedirect(urlFinal);



    }

    /**
     */
    protected void rollback(Connection connection) {
        try {
            connection.rollback();
        } catch (Exception e) {
            log.log(Level.FINEST, "Rollback se nezdařil", e);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/xhtml+xml;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
